'use strict';

/* Services */

angular.module('myApp.IMServices', ['myApp.MessageModel','myApp.DataView']).
	factory('IMService', ['$rootScope','$interval','$timeout','Message','MessageView','DataView',function ($rootScope,$interval,$timeout,Message,MessageView,DataView) {//跟IM通信的位置
		var socket = null;
		var offline =  false;
        var reconnectionCount = 0;
		
		function init(option){
			if (!(window.WebSocket || window.MozWebSocket)) {
                swal({title : '你的浏览器不支持WebSocket,请升级！', timer : 2000, showConfirmButton : false});
                return;
		    }
		    window.WebSocket = window.WebSocket || window.MozWebSocket;
		    option = option || {};
	        option.port = parseInt(option.port) || '80';
	        option.path = option.path ? option.path.charAt(0) != '/' ? '/' + option.path : option.path : '';
	        socket = new WebSocket('ws://' + option.domain + ':' + option.port + option.path);
	        socket.binaryType = 'arraybuffer';
	        socket.onopen = function () {
	        	//console.log('WebSocket 链接成功！');
	        	offline = false;
                reconnectionCount = 0;
	            sendToken(option.sessionToken);
	            sendSignal();
	        };
	        socket.onmessage = function (evt) {
	            if (!evt.data)
	                return;
	            var message = wsutil.unPackMsg(evt.data);
	            //console.log(message);
	            MessageView.receive(message, send);
	            
	        };
	        socket.onerror = function (data) {
	        	//console.log('IM通道出现错误！');
                reconnect()
	        };
	        socket.onclose = function (data) {
	        	//console.log('IM通道关闭！');
                reconnect();
	        };
		};
		function sendToken(sessionToken){
			//console.log('WebSocket 发送Token验证！');
			var message = new Message.RequestMessage(sessionToken);
			message = wsutil.packMsg(message, 3);
			if (socket && socket.readyState == socket.OPEN){
				socket.send(message);
			}else{
                //console.info('发送请求失败, 重新连接IM服务器');
                reconnect();
			}
		}
		
		//发送心跳
        var signalInterval = null;
		function sendSignal(){
			var message = null;
            if(signalInterval != null) clearInterval(signalInterval);
            signalInterval = $interval(function () {
                message = new Message.BeatHeartMessage();
                message = wsutil.packMsg(message, 2);
                if (socket && socket.readyState == socket.OPEN)
                    socket.send(message);
                else {
                    //console.info('WebSocket 发送心跳失败');
                }
            }, 1 * 60 * 1000);
		}
		
		function send(message){
            if($rootScope.currentChatObj && $rootScope.currentChatObj.invalid){
                return;
            }
			if (socket && socket.readyState == socket.OPEN) {
				//console.log(message);
				message = wsutil.packMsg(message, 1);
				socket.send(message);
			}else{
				//console.info('WebSocket消息发送失败');
			}
		};
		function checkSendState(){
			$interval(function(){
				var thisTime = new Date().getTime();
				$rootScope.messages = util.checkSendStats($rootScope.messages, thisTime, $rootScope.chatsMap);
            },1*3*1000);
		}

        function reconnect(){
            reconnectionCount++;
            if(reconnectionCount > 3){//重连超过3次，返回登录页面
                swal({  title: "服务器连接失败，点击确认返回登录界面重新登录。",
                        showConfirmButton : true,
                        confirmButtonText: "确认",
                        closeOnConfirm: false },
                    function () {
                        window.location = 'login.do';
                    });
                return;
            }
            //console.log('重新连接IM服务器');
            DataView.initPromise().then(function (user) {
                //链接IM
                var option = {
                    domain: user.host,
                    port: 10001,
                    path: '/websocket',
                    sessionToken: user.sessionToken
                };
                init(option);
            }, function (errorMsg) {
                //console.log(errorMsg);
                $timeout(reconnect, 10*1000);
            });
        }

		function quit(callback){
			if (socket && socket.readyState == socket.OPEN) {
				var message = new Message.QuitMessage();
				message = wsutil.packMsg(message, 5);
				socket.send(message);
			}else if(callback && angular.isFunction(callback)){
				callback();
			}
		};
		return {
			init : function(option){
				init(option);
			},
			send: function(message){
				send(message);
			},
			close: function () {
                socket.close();
            },
            checkSendState:function(){
            	checkSendState();
            },
            quit: function(callback){
            	quit(callback);
            }
		};
	}]);


